// pages/home-music/index.js
import {
  rankingStore,
  rankingMap,
  playerStore
} from "../../store/index"


import {
  APIMusic
} from "../../service/api_music"

import {
  getRectBySelector
} from "../../utils/selector-rect"

import {
  throttle
}
from "../../utils/throttle.js"

const throllteSelectorRect = throttle(getRectBySelector, 100)

Page({

  /**
   * 页面的初始数据
   */
  data: {
    swiperHeight: 0,
    banners: [],
    // 推荐歌曲
    recommendSongs: [],
    // 热门歌单
    hotSongMenu: [],
    // 推荐歌单
    recommendSongMenu: [],
    // 巅峰榜单
    rankings: {},
    currentSong: {}, //当前正在播放的歌曲
    isPlaying:false, // 歌曲的播放状态
    playAnimState:"paused" // 歌曲动画 状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getPageData();

    // 1 监听推荐歌曲
    rankingStore.dispatch("getRankingDataAction");
    rankingStore.onState("hotRanking", res => {
      if (!res.tracks) return
      const recommendSongs = res?.tracks.slice(0, 6)
      this.setData({
        recommendSongs
      })
    })

    rankingStore.onState("newRanking", this.getRankingHandler(3779629))
    rankingStore.onState("upRanking", this.getRankingHandler(19723756))
    rankingStore.onState("originRanking", this.getRankingHandler(2884035))
    rankingStore.onState("blackVipRanking", this.getRankingHandler(5453912201))

    // 2 监听当前正在播放的歌曲
    playerStore.onStates(["songInfo","isPlaying"], ({
      songInfo,isPlaying
    }) => {
      if (songInfo) {
        this.setData({
          currentSong: songInfo
        })
      }

      if(isPlaying !== undefined){
        this.setData({ 
          isPlaying,
          playAnimState:isPlaying?'runing':'paused'
        })
      }
    })
  },


  // 获取页面数据
  getPageData() {
    // 1 轮播图
    APIMusic.getBanners().then(res => {
      // setData 是异步还是同步？
      // setData 在设置data的数据上；是同步的
      // 通过最新的数据对 wxml 进行数据更新；渲染的过程是异步的
      this.setData({
        banners: res.banners
      })
      // 意味着这里可以拿到更新后的数据
      // console.log(this.data.banners);
    }).catch(err => {
      console.error(err);
    })

    // 2 热门歌单
    APIMusic.getHotSongMenu().then(res => {
      this.setData({
        hotSongMenu: res.playlists
      })
    }).catch(err => {
      console.error(err);
    })

    // 3 推荐歌单
    APIMusic.getRecommendMenu(10).then(res => {
      this.setData({
        recommendSongMenu: res.result
      })
    }).catch(err => {
      console.error(err);
    })
  },

  // 轮播图图片加载完成
  handleImageLoad() {
    throllteSelectorRect(".swiper-image").then(res => {
      this.setData({
        swiperHeight: res[0].height
      })
    })
  },

  // 跳转到搜索页面
  handleSearchClick() {
    wx.navigateTo({
      url: "packageDetail/pages/detail-serach/index",
    })
  },

  // 点击推荐更多 按钮
  handleClickRecommendMore() {
    this.handleJumpSongDetailPage("hotRanking")
  },

  // 点击推荐歌曲 将该歌曲所属列表 和 当前歌曲的在列表里面的索引保存
  handleClickRecommendSong(event) {
    const index = event.currentTarget.dataset.index;
    playerStore.setState("playListSongs", this.data.recommendSongs);
    playerStore.setState("playSongIndex", index)
  },


  // 点击榜单
  handleClickRanking(event) {
    let idx = event.currentTarget.dataset.idx
    this.handleJumpSongDetailPage(rankingMap[idx])
  },

  // 跳转到 榜单详情界面
  handleJumpSongDetailPage(rankingName) {
    wx.navigateTo({
      url: `/packageDetail/pages/detail-songs/index?ranking=${rankingName}&type=ranking`,
    })
  },

  // 点击暂停 或 播放
  handlePalyBtnClick(){
    playerStore.dispatch("changeMusicPlayStatusAction",!this.data.isPlaying)
  },

  // 点击 playBar 跳转到歌曲播放页
  handlePlayBarClick(event){
    wx.navigateTo({
      url: '/packagePlayer/pages/music-palyer/index?id=' + this.data.currentSong.id,
    })
  },

  // 获取数据
  getRankingHandler(idx) {
    return (res) => {
      if (!Object.keys(res).length) return
      const id = res.id
      const name = res.name;
      const coverImgUrl = res.coverImgUrl;
      const songList = res.tracks.slice(0, 3);
      const playCount = res.playCount
      const newRankingObj = {
        name,
        coverImgUrl,
        songList,
        playCount,
        id
      }
      const OriginObj = this.data.rankings
      let newObj = {
        ...OriginObj,
        [idx]: newRankingObj
      }
      this.setData({
        rankings: newObj
      })
    }
  }
})